﻿Imports OpenNETCF.Desktop.Communication
Imports System.IO
Imports System.ComponentModel


Class MainWindow
    Private WithEvents _backgroundWorker As BackgroundWorker
    Public Shared v_username As String
    Dim FileFound As Integer
    Dim SearchCriteria As String = My.Settings.SearchCriteria
    Dim oRapi As RAPI
    Dim localLocation As String = My.Settings.localLocation
    Dim remoteLocation As String = My.Settings.remoteLocation
    Dim retainFilesonReader As Boolean = My.Settings.retainFilesonReader
    Dim successRecordCtr As Integer = 0
    Dim duplicateRecordCtr As Integer = 0
    Dim noRecordRecordCtr As Integer = 0
    Dim remotefileCount As Integer = 0
    Dim path As String = localLocation
    Dim CriteriaPath, files, filename As String
    Dim duplicatesCtr As Integer = 0
    Dim notRelatedToAnyAsset As Integer = 0
    Dim fileCtr As Integer = 0
    Dim v_isdirty As Boolean = False
    Dim readerSynchLog As New List(Of String)

    Dim rfidScanHistoryDS As New RFIDScanHistoryTableAdapters.RFIDScanHistoryTableAdapter
    Dim mainAssetTableDS As New MainAssetTableDataSetTableAdapters.MainAssetsTableTableAdapter


    Private Sub RibbonButtonSynch_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles RibbonButtonSynch.Click
        gridControlsView(DockpanelSynch)


        Label1.Content = Now.ToShortDateString
        oRapi = New RAPI
        If Not oRapi.DevicePresent Then
            connectedNo.Visibility = Windows.Visibility.Visible
            connectedYes.Visibility = Windows.Visibility.Collapsed
            panelConnectToReader.Visibility = Windows.Visibility.Visible
            panelExtractFiles.Visibility = Windows.Visibility.Hidden
        Else
            connectedNo.Visibility = Windows.Visibility.Collapsed
            connectedYes.Visibility = Windows.Visibility.Visible
            panelExtractFiles.Visibility = Windows.Visibility.Visible
            panelConnectToReader.Visibility = Windows.Visibility.Hidden

        End If

    End Sub

    Private Sub buttonReaderSettings_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonReaderSettings.Click
        gridControlsView(GridSettings)
    End Sub

    Private Sub DisplayLoginScreen()
        Dim frm As New frmLogin()

        frm.Owner = Me
        frm.ShowDialog()
        If frm.DialogResult.HasValue And frm.DialogResult.Value Then
            'MessageBox.Show("User Logged In")
            labelUser.Content = frm.txtUserName.Text
        Else
            Application.Current.Shutdown()
        End If
    End Sub

    Private Sub ATSMain_Loaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        '===================================================
        'change later if log in resolved
        'DisplayLoginScreen()
        labelUser.Content = Environment.UserName
        '===================================================


        gridControlsView(DockpanelSynch)

        LoadDefaults()
        v_isdirty = False

        Label1.Content = Now.ToShortDateString
        oRapi = New RAPI
        If Not oRapi.DevicePresent Then
            connectedNo.Visibility = Windows.Visibility.Visible
            connectedYes.Visibility = Windows.Visibility.Collapsed
            panelConnectToReader.Visibility = Windows.Visibility.Visible
            panelExtractFiles.Visibility = Windows.Visibility.Hidden
        Else
            connectedNo.Visibility = Windows.Visibility.Collapsed
            connectedYes.Visibility = Windows.Visibility.Visible
            panelExtractFiles.Visibility = Windows.Visibility.Visible
            panelConnectToReader.Visibility = Windows.Visibility.Hidden

        End If
    End Sub

    Private Function IsDeviceConnected() As Boolean
        Try
            If oRapi.DevicePresent Then
                oRapi.Connect()
                If oRapi.Connected Then
                    connectedNo.Visibility = Windows.Visibility.Collapsed
                    connectedYes.Visibility = Windows.Visibility.Visible
                    Return True
                Else
                    connectedNo.Visibility = Windows.Visibility.Visible
                    connectedYes.Visibility = Windows.Visibility.Collapsed
                End If
            End If
        Catch ex As Exception
            If MsgBox("Cannot connect to the device. " & ControlChars.Lf & ControlChars.Lf & ex.Message.ToString & ControlChars.Lf & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Device not found") = MsgBoxResult.Yes Then
                Return True
            End If
            Return False
        End Try
        If MsgBox("Cannot connect to the device." & ControlChars.Lf & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Device not found") = MsgBoxResult.Yes Then
            Return True
        End If
        Return False
    End Function

    Private Function FilesFoundOnDevice() As Boolean
        Dim files As Boolean = False
        Dim di As DirectoryInfo

        Try
            remotefileCount = 0
            If Not oRapi.EnumFiles(remoteLocation & "*.txt") Is Nothing Then
                remotefileCount = oRapi.EnumFiles(remoteLocation & "*.txt").Count
            End If
            If remotefileCount > 0 Then
                Try
                    di = New DirectoryInfo(localLocation)
                    If Not di.Exists Then
                        di.Create()
                    End If
                    For int As Integer = 0 To remotefileCount - 1
                        Try
                            oRapi.CopyFileFromDevice(localLocation & oRapi.EnumFiles(remoteLocation & "*.txt").Item(int).FileName, remoteLocation & oRapi.EnumFiles(remoteLocation & "*.txt").Item(int).FileName, True)
                            files = True
                        Catch RAPIerr As RAPIException
                            If MsgBox(RAPIerr.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                                files = True
                            End If
                        Catch ex As Exception
                            If MsgBox(ex.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                                files = True
                            End If
                        End Try
                    Next
                Catch ex As Exception
                    If MsgBox(ex.ToString & remoteLocation.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                        files = True
                    End If
                End Try
            Else
                If MsgBox("No files found under reader directory " & remoteLocation.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                    files = True
                End If
            End If
        Catch RAPIerr As RAPIException
            If MsgBox(RAPIerr.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed.") = MsgBoxResult.Yes Then
                files = True
            End If
        Catch ex As Exception
            If MsgBox("No files found at reader location: " & remoteLocation.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                files = True
            End If
        Finally
        End Try
        oRapi.Disconnect()
        Return files
    End Function

    Private Sub removeFilesFromDevice()
        Try
            oRapi.Connect()
            If oRapi.Connected Then
                Dim fileCount As Integer = oRapi.EnumFiles(remoteLocation & "*.txt").Count
                For int As Integer = 0 To fileCount - 1
                    Try
                        oRapi.DeleteDeviceFile(remoteLocation & oRapi.EnumFiles(remoteLocation & "*.txt").Item(0).FileName)
                    Catch RAPIerr As RAPIException
                        MsgBox(RAPIerr.ToString, MsgBoxStyle.Information, "Failed to remove files. Reconnect device and try again")
                    End Try
                Next
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Information, "Failed to remove files. Reconnect device and try again")
        End Try
        oRapi.Disconnect()
    End Sub

    Private Sub UpdateRFIDData()
        busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Visible

        _backgroundWorker = New BackgroundWorker
        _backgroundWorker.RunWorkerAsync()
    End Sub

    Sub processFiles()

        readerSynchLog = New List(Of String)
        Dim currentRow() As String
        Dim fldCtr As Integer


        SearchCriteria = String.Empty

        Try


            CriteriaPath = path.Substring(0, path.LastIndexOf("\"))

            If SearchCriteria.Length = 0 Then
                SearchCriteria = "*.txt"
            Else
                SearchCriteria = path.Substring(path.LastIndexOf("\") + 1)
            End If

            If Directory.GetFiles(CriteriaPath, SearchCriteria).Count > 0 Then




                'Using New OperationContextScope(auth.InnerChannel)
                '    Dim result = auth.Login("admin", "joko123!", True, "").RootResults.FirstOrDefault()

                '    ' Extract the cookie embedded in the received web service response
                '    ' and stores it locally
                '    'Dim response As HttpResponseMessageProperty = DirectCast(OperationContext.Current.IncomingMessageProperties(HttpResponseMessageProperty.Name), HttpResponseMessageProperty)
                '    'sharedCookie = response.Headers("Set-Cookie")
                'End Using

                For Each files In Directory.GetFiles(CriteriaPath, SearchCriteria)
                    fileCtr += 1

                    filename = Mid(files, localLocation.Length + 1, files.Length - localLocation.Length + 1)

                    Dim parser As New FileIO.TextFieldParser(files)
                    parser.TextFieldType = FileIO.FieldType.Delimited
                    parser.SetDelimiters(" ")
                    While Not parser.EndOfData
                        parser.ReadFields()
                    End While
                    parser.Close()
                    parser = New FileIO.TextFieldParser(files)
                    parser.TextFieldType = FileIO.FieldType.Delimited
                    parser.SetDelimiters(" ")
                    While Not parser.EndOfData
                        fldCtr = 1
                        Try
                            currentRow = parser.ReadFields()
                            Dim currentField As String
                            For Each currentField In currentRow
                                If fldCtr = 2 Then
                                    Dim rfidNumber As String = Mid(currentRow(1), currentRow(1).Length - 9, 10)
                                    Dim rfidScanDate As Date = CDate(Mid(filename, 1, 4) & "/" & Mid(filename, 5, 2) & "/" & Mid(filename, 7, 2))

                                    If rfidScanHistoryDS.GetDataByRFIDNUMandSCANDATE(rfidNumber, rfidScanDate).Count = 0 Then
                                        rfidScanHistoryDS.InsertScanHistory(rfidNumber, rfidScanDate)

                                        Dim mainAssetDetail = From asset In mainAssetTableDS.GetDataByRFIDNo(rfidNumber)

                                        If mainAssetDetail.Count > 0 Then
                                            mainAssetTableDS.UpdateMainAssetTableLastScanDate("me", rfidNumber)
                                            readerSynchLog.Add(New String("Update" & ControlChars.Lf & "Asset No - " & mainAssetDetail.First.Assetno & ControlChars.Lf & "RFID No - " & rfidNumber & ControlChars.Lf & " Scan Date - " & rfidScanDate))
                                        Else
                                            readerSynchLog.Add(New String("Not Related to an Asset" & ControlChars.Lf & "RFID No - " & rfidNumber & ControlChars.Lf & " Scan Date - " & rfidScanDate))
                                            notRelatedToAnyAsset += 1
                                        End If
                                    Else
                                        readerSynchLog.Add(New String("Duplicate" & ControlChars.Lf & "RFID No - " & rfidNumber & ControlChars.Lf & " Scan Date - " & rfidScanDate))
                                        duplicatesCtr += 1
                                    End If
                                End If
                                fldCtr += 1
                            Next
                        Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                            MsgBox("Line " & ex.Message & _
                            "is not valid and will be skipped.")
                        End Try
                    End While
                    parser.Close()
                    FileFound += 1
                    If File.Exists(files) Then
                        File.Move(files, Mid(files, 1, files.Length - 3) & Format(Now(), "ddMMyyhhmmss"))
                    Else
                        File.Move(files, Mid(files, 1, files.Length - 3) & "old")
                    End If
                Next
            Else
                Throw New Exception("No reader files exists at " & CriteriaPath)
            End If

        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonProcessReaderFiles.Click
        If IsDeviceConnected() Then

            If oRapi IsNot Nothing Then

                If FilesFoundOnDevice() Then
                    If remotefileCount > 0 Then

                        If Not retainFilesonReader Then
                            removeFilesFromDevice()
                        End If

                    End If

                    UpdateRFIDData()

                End If

            Else

                UpdateRFIDData()
            End If

        End If

    End Sub

    Private Sub ButtonConnectToReader_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles ButtonConnectToReader.Click
        If oRapi.DevicePresent Then
            oRapi.Connect()
            If oRapi.Connected Then
                connectedNo.Visibility = Windows.Visibility.Collapsed
                connectedYes.Visibility = Windows.Visibility.Visible
                panelExtractFiles.Visibility = Windows.Visibility.Visible
                panelConnectToReader.Visibility = Windows.Visibility.Hidden
            Else
                connectedNo.Visibility = Windows.Visibility.Visible
                connectedYes.Visibility = Windows.Visibility.Collapsed
                panelConnectToReader.Visibility = Windows.Visibility.Visible
                panelExtractFiles.Visibility = Windows.Visibility.Hidden
            End If
        End If
    End Sub


    Private Sub _backgroundWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles _backgroundWorker.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        processFiles()
    End Sub

    Private Sub _backgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles _backgroundWorker.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            LabelNoAsset.Content = notRelatedToAnyAsset
            LabelDuplicates.Content = duplicatesCtr
            LabelNumberofFilesProcessed.Content = fileCtr
            listboxSynchLog.ItemsSource = readerSynchLog
        End If
        busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Collapsed
    End Sub

#Region "Support Procedures"
    Private Sub SetWindowProperties(dirty As Boolean)
        If dirty Then
            Me.Title &= IIf(Not Me.Title.ToUpper.Contains("UNSAVED"), " (unsaved)", "")
        Else
            Me.Title = IIf(Title.ToUpper.Contains("UNSAVED"), Me.Title.Substring(0, Me.Title.Length - 10), Me.Title)
        End If
    End Sub

    Private Sub LoadDefaults()
        textboxBackupFilesLocation.Text = My.Settings.localLocation
        textboxReaderFilesLocation.Text = My.Settings.remoteLocation
        cbRemoveFilesFromReader.IsChecked = My.Settings.removeFilesonReader

        cbReaderFileHeaderFirstRow.IsChecked = My.Settings.readerFirstRowHeader
        textboxRFIDNumLength.Text = My.Settings.readerRFIDNumberLength
        textboxReaderDelimiter.Text = My.Settings.readerRowDelimiter
        textboxReaderFileExtension.Text = My.Settings.readerFileExtension
        textboxReaderRowFormat.Text = My.Settings.readerRowFormat
        cbReaderCreateAssetData.IsChecked = My.Settings.readerCreateAssetData

        SetWindowProperties(False)
    End Sub
#End Region

#Region "Control Events"

    Private Sub buttonSave_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles BtnSaveSettings.Click
        If v_isdirty Then
            My.Settings.localLocation = textboxBackupFilesLocation.Text
            My.Settings.remoteLocation = textboxReaderFilesLocation.Text
            My.Settings.removeFilesonReader = cbRemoveFilesFromReader.IsChecked

            My.Settings.readerFirstRowHeader = cbReaderFileHeaderFirstRow.IsChecked
            My.Settings.readerRFIDNumberLength = textboxRFIDNumLength.Text
            My.Settings.readerRowDelimiter = textboxReaderDelimiter.Text
            My.Settings.readerFileExtension = textboxReaderFileExtension.Text
            My.Settings.readerRowFormat = textboxReaderRowFormat.Text
            My.Settings.readerCreateAssetData = cbReaderCreateAssetData.IsChecked

            My.Settings.Save()
            v_isdirty = False
            SetWindowProperties(False)
            MessageBox.Show("Data has been saved successfully.", "ATS", MessageBoxButton.OK, MessageBoxImage.Information)
        Else
            MessageBox.Show("Nothing saved, values were not changed.", "ATS", MessageBoxButton.OK, MessageBoxImage.Information)
        End If
    End Sub
    Private Sub buttonRefresh_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles BtnRefreshSettings.Click
        If v_isdirty = True Then

            If MessageBox.Show("There are unsaved entries. Do you really want refresh the data?", "Refresh", MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                LoadDefaults()
            End If
        Else
            LoadDefaults()

        End If
    End Sub

    Private Sub buttonBrowseReader_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonBrowseReader.Click
        Dim ownedWindow As New BrowseDevice
        Try
            ownedWindow.Path = textboxReaderFilesLocation.Text
            ownedWindow.ShowDialog()

            If ownedWindow.OkCancel = "OK" Then
                textboxReaderFilesLocation.Text = ownedWindow.Path
            Else
                ownedWindow.Close()
                ownedWindow = Nothing
            End If
        Catch ex As Exception
            ownedWindow.Close()
            MsgBox("Please check if your device is connected.", MsgBoxStyle.OkOnly, "Connecting to device...")
        End Try
    End Sub

    Private Sub buttonBrowseBackup_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonBrowseBackup.Click
        Dim dlg As New System.Windows.Forms.FolderBrowserDialog
        dlg.SelectedPath = textboxBackupFilesLocation.Text
        If dlg.ShowDialog() = Forms.DialogResult.OK Then
            textboxBackupFilesLocation.Text = dlg.SelectedPath & "\"
        Else
            textboxBackupFilesLocation.Text = My.Settings.localLocation
        End If
    End Sub
    Private Sub textboxBackupFilesLocation_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles textboxBackupFilesLocation.TextChanged
        v_isdirty = True
        SetWindowProperties(True)
    End Sub
    Private Sub textboxReaderFilesLocation_TextChanged(sender As Object, e As System.Windows.Controls.TextChangedEventArgs) Handles textboxReaderFilesLocation.TextChanged
        v_isdirty = True
        SetWindowProperties(True)
    End Sub

    Private Sub cbRemoveFilesFromReader_Checked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles cbRemoveFilesFromReader.Checked, cbRemoveFilesFromReader.Unchecked
        v_isdirty = True
        SetWindowProperties(True)
    End Sub
    Private Sub cbReaderFileHeaderFirstRow_Checked(sender As Object, e As System.Windows.RoutedEventArgs) Handles cbReaderFileHeaderFirstRow.Checked, cbReaderFileHeaderFirstRow.Unchecked
        v_isdirty = True
        SetWindowProperties(True)
    End Sub
    Private Sub textboxRFIDNumLength_TextChanged(sender As Object, e As System.Windows.Controls.TextChangedEventArgs) Handles textboxRFIDNumLength.TextChanged
        v_isdirty = True
        SetWindowProperties(True)
    End Sub
    Private Sub textboxReaderDelimiter_TextChanged(sender As Object, e As System.Windows.Controls.TextChangedEventArgs) Handles textboxReaderDelimiter.TextChanged
        v_isdirty = True
        SetWindowProperties(True)
    End Sub
    Private Sub textboxReaderFileExtension_TextChanged(sender As Object, e As System.Windows.Controls.TextChangedEventArgs) Handles textboxReaderFileExtension.TextChanged
        v_isdirty = True
        SetWindowProperties(True)
    End Sub
    Private Sub textboxReaderRowFormat_TextChanged(sender As Object, e As System.Windows.Controls.TextChangedEventArgs) Handles textboxReaderRowFormat.TextChanged
        v_isdirty = True
        SetWindowProperties(True)
    End Sub
    Private Sub cbReaderCreateAssetData_Checked(sender As Object, e As System.Windows.RoutedEventArgs) Handles cbReaderCreateAssetData.Checked, cbReaderCreateAssetData.Unchecked
        v_isdirty = True
        SetWindowProperties(True)
    End Sub
#End Region



#Region "DB Backup"
    'Dim WithEvents oBackup As New Backup

    ''--Method to take backup

    'Private Sub BackupSqlDatabase()

    '    Dim conn As New ServerConnection(serverName, userName, passWd) ' -- set SQL server connection given the server name, user name and password
    '    Dim oSQLServer As New Server(conn) '--create the SMO server object using connection

    '    Dim OrigBackupPath As String = oSQLServer.Information.MasterDBPath.Replace("\DATA", "\Backup\DB_BACKUP_NAME.BAK") ' -- set the path where backup file will be stored

    '    Dim bkDevItem As New BackupDeviceItem(OrigBackupPath, DeviceType.File) ' -- create SMO.Backupdevice object

    '    With oBackup ' Set the backup object property 
    '        .Action = BackupActionType.Database
    '        .Database = YOUR_DATABASE_NAME
    '        .Devices.Add(bkDevItem)
    '        .Initialize = True
    '        .Checksum = True
    '        .ContinueAfterError = True
    '        .Incremental = False
    '        .LogTruncation = BackupTruncateLogType.Truncate
    '        .SqlBackup(oSQLServer) ' backup SQL database
    '    End With

    'End Sub
#End Region

    Private Sub RibbonButtonDBBackup_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles RibbonButtonDBBackup.Click
        gridControlsView(GridBackup)
        'DockpanelSynch.Visibility = Windows.Visibility.Collapsed
        'GridSettings.Visibility = Windows.Visibility.Collapsed
        'GridBackup.Visibility = Windows.Visibility.Visible


    End Sub

    Sub gridControlsView(gridControls As Object)
        DockpanelSynch.Visibility = Windows.Visibility.Collapsed
        GridSettings.Visibility = Windows.Visibility.Collapsed
        GridBackup.Visibility = Windows.Visibility.Collapsed
        GridRestore.Visibility = Windows.Visibility.Collapsed

        gridControls.Visibility = Windows.Visibility.Visible
    End Sub

    Private Sub ButtonBrowseBackupLocation_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonBrowseBackupLocation.Click
        Dim dlg As New System.Windows.Forms.FolderBrowserDialog
        If dlg.ShowDialog() = Forms.DialogResult.OK Then
            backupFileLocation.Text = dlg.SelectedPath
        End If
    End Sub

    Private Sub ButtonCreateBackup_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonCreateBackup.Click
        'Dim dlg As New System.Windows.Forms.FolderBrowserDialog
        Dim backuplocation As String = "c:"
        If backupFileLocation.Text.Length > 0 Then
            backuplocation = backupFileLocation.Text
        End If
        Try
            'If SQLClass.SQLBackupDatabase( "jokoatsnew.mssql.somee.com", "jokoatsnew", backuplocation & "\ATS" & Now.ToString("yyyyMMdd") & ".bak") Then
            If SQLClass.SQLBackupDatabase(My.Settings.databaseServer, My.Settings.databaseName, backuplocation & "\ATS" & Now.ToString("yyyyMMdd") & ".bak") Then
                MessageBox.Show("ATS database backup successful : " & backuplocation & "\ATS" & Now.ToString("yyyyMMdd") & ".bak")
            Else
                Throw New Exception("Please check Event viewer for details of the error.")
            End If
        Catch ex As Exception
            MessageBox.Show("Failed to create backup file. Error : " & ex.ToString)
        End Try

    End Sub

    Private Sub ButtonBrowseRestoreLocation_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonBrowseRestoreLocation.Click
        Dim dlg As New Microsoft.Win32.OpenFileDialog()
        If dlg.ShowDialog() Then
            RestoreFileLocation.Text = dlg.FileName
        End If
        If RestoreFileLocation.Text.Length > 0 Then
            ButtonRestoreDatabase.IsEnabled = True
        End If
    End Sub

    Private Sub ButtonRestoreDatabase_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonRestoreDatabase.Click
        Try
            Dim messageBoxText As String = RestoreFileLocation.Text & ControlChars.Lf & "Do you really want to restore from this backup file? This will overwrite the current data in the database."
            Dim caption As String = "Restore ATS database"
            Dim button As MessageBoxButton = MessageBoxButton.OKCancel
            Dim icon As MessageBoxImage = MessageBoxImage.Warning

            If MessageBox.Show(messageBoxText, caption, button, icon) = MessageBoxResult.OK Then
                If SQLClass.SQLRestoreDatabase(My.Settings.databaseServer, My.Settings.databaseName, RestoreFileLocation.Text) Then
                    MessageBox.Show("ATS database restore successful : " & RestoreFileLocation.Text)
                Else
                    Throw New Exception("Please check Event viewer for error details.")

                End If

            End If
        Catch ex As Exception
            MessageBox.Show("Failed to restore from backup file. Error : " & ex.ToString)
        End Try
    End Sub

    Private Sub RibbonButtonDBRestore_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles RibbonButtonDBRestore.Click
        gridControlsView(GridRestore)
    End Sub
End Class
